package dart.play

import dart.Attempt
import dart.Game
import dart.PlayerGame
import dart.Util

class GamePlayController {
	def index = {
		Game game = Game.get(params.id);
		
		if (!game)
			render(view: 'newGame')
		else if (game.status == Game.COMPLETED)
			render(view: 'gameOver', model: [game: game])
		else
			render(view: 'play', model: [game: game])
	}

	def create = {
		Util.validateScoreParam(params, 'startingScore')
		Util.validateScoreParam(params, 'endingScore')
		Util.validateScoreParam(params, 'scoreLimit')

		if( params['bounceBack'] == 'off'){
			params['bounceBack'] = (params['countDown'] == 'true' ? '-1000000' : '1000000')
		}

		Util.validateScoreParam(params, 'bounceBack')

		Game game = new Game(params);
		if (!game.hasErrors() && game.save(flush: true)) {
			redirect(action:game, params: [id: game.id] );
		} else {
			flash.message = 'There was a problem starting the game.'
			flash.error = game.errors.fieldError
			render(view: 'newGame')
		}
	}

	def calculate = {
		Game game = Game.get(params.id);
		PlayerGame playerGame = game.playerGames[game.currentPlayer] as PlayerGame;

		List attempts = []
		(0..2).each {
			attempts << Attempt.create(params["attempt[$it]"] as Map, game);
		}

		Float endScore = playerGame.newRound(attempts);

		if (params['remote'] == 'true'){
			String output = "";
			Float total = 0;
			attempts.each{
				Float score = it.score;
				output += "$score|";
				total += score;
			};
			output += "$total|$endScore";
			render output
			game.discard();
		}else{
			game.nextPlayer(endScore)
			game.save(flush: true)
			redirect(action:game, params: [id: game.id] );
		}
	}
}